package cn.tedu.ps;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeoutException;

public class PSConsumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //设置连接信息
        ConnectionFactory cf = new ConnectionFactory();
        cf.setHost("192.168.144.160");
        cf.setUsername("guest");
        cf.setPassword("guest");
        //创建tcp连接
        Connection nc = cf.newConnection();
        Channel cc = nc.createChannel();
        //定义一个队列：随机队列名、非持久、独占的、自动删除的队列
        String queueName = cc.queueDeclare().getQueue();//无参构造可以满足我们的需求
        //定义一个交换机，如果服务器中有指定的交换机直接使用，如果没有就创建
        cc.exchangeDeclare("logs","fanout");
        //绑定交换机和队列
        cc.queueBind(queueName,"logs","");
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String s, Delivery delivery) throws IOException {
                //消息封装到了delivery对象中
                byte[] body = delivery.getBody();
                String msg = new String(body);
                //拿到消息后，我们进行处理，为了模拟耗时操作，设计遇到一个'.',就休息1s
                System.out.println("接收到消息："+msg);
                for (int i = 0; i < msg.length(); i++) {
                    if (msg.charAt(i)=='.'){
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                System.out.println(msg+"处理完毕");
            }
        };
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String s) throws IOException {

            }
        };
        cc.basicConsume(queueName,true,deliverCallback,cancelCallback);
    }
}
